package ${servicePackageName}.service.sys.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${commonPackageName}.enums.ExceptionEnum;
import ${commonPackageName}.exception.BusinessException;
import ${commonPackageName}.utils.AssertUtil;
import ${commonPackageName}.utils.TreeListUtil;
import ${servicePackageName}.dto.DepartmentTreeParentDto;
import ${servicePackageName}.entity.sys.SysDepartment;
import ${servicePackageName}.mapper.sys.SysDepartmentMapper;
import ${servicePackageName}.mapstruct.DepartmentConverMapper;
import ${servicePackageName}.qo.sys.DepartmentReq;
import ${servicePackageName}.service.sys.ISysDepartmentService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;

/**
 * <p>
 * 机构部门表 服务实现类
 * </p>
 *
 * @author lizihao
 * @since 2020-11-18
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdateUser(DepartmentReq departmentReq) throws Exception {
		if(null == departmentReq.getId()) {
			SysDepartment dept = DepartmentConverMapper.INSTANCES.departmentReqToSysDepartment(departmentReq);
			dept.setSortNum(this.baseMapper.getMaxOrderNum(Long.valueOf(departmentReq.getParentDepId()))+1);
			this.baseMapper.insert(dept);
		}else {
			//id跟parentid不能是同一个
			AssertUtil.isTrue(departmentReq.getId().equals(departmentReq.getParentDepId()),() -> new BusinessException(ExceptionEnum.REPEAT_VALUE));
			SysDepartment dept = DepartmentConverMapper.INSTANCES.departmentReqToSysDepartment(departmentReq);
			this.baseMapper.updateById(dept);
		}
		
	}

	@Override
	public List<DepartmentTreeParentDto> getAllDepartment() throws Exception{
		return TreeListUtil.getTreeList(this.baseMapper.getAllDepartment(), 
				MapUtil.of(new String[][] {
				     {"nameKey", "departmentName"},
				     {"weightKey", "sortNum"},
				     {"idKey", "id"},
				     {"parentIdKey", "parentDepId"}
				}), ListUtil.of("parentDepId","isShow"), DepartmentTreeParentDto.class);
	}

	@Override
	public List<DepartmentTreeParentDto> getAllDepartmentWithUser(Long userId) throws Exception{
		return TreeListUtil.getTreeList(this.baseMapper.getAllDepartmentWithUser(userId), 
				MapUtil.of(new String[][] {
				     {"nameKey", "departmentName"},
				     {"weightKey", "sortNum"},
				     {"idKey", "id"},
				     {"parentIdKey", "parentDepId"}
				}), ListUtil.of("parentDepId","isShow"), DepartmentTreeParentDto.class);
	}

}
